package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Equivalence;
import com.itheima.admin.mapper.DeptMapper;
import com.itheima.admin.service.IDeptService;
import com.itheima.pojo.dto.DeptDto;
import com.itheima.pojo.dto.PageDto;
import com.itheima.pojo.pojo.Dept;
import com.itheima.pojo.vo.DeptVo;
import com.itheima.pojo.vo.PageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl implements IDeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public PageVo<DeptVo> queryByPage(PageDto pageDto) {
        //开启分页
        PageHelper.startPage(pageDto.getCurrentPage(), pageDto.getPageSize());

        PageInfo<Dept> page =  new PageInfo<>(deptMapper.DeptQueryByPage(pageDto.getStatus(),pageDto.getUsername()));

        List<DeptVo> list = page.getList().stream().map(
                dept -> {
                    DeptVo deptVo = new DeptVo();
                    BeanUtils.copyProperties(dept,deptVo);
                    deptVo.setStatus(dept.getState()==1?"使用中":"禁用");
                    return deptVo;
                }
        ).collect(Collectors.toList());

        return new PageVo<DeptVo>(list,Long.valueOf(page.getTotal()).intValue());
    }

    @Override
    public Boolean addDept(DeptDto deptDto, HttpSession session) {
        Dept dept=new Dept();
        dept.setDeptId(UUID.randomUUID().toString());
        dept.setState(deptDto.getStatus());
        session.setAttribute("deptId",dept.getDeptId());
        BeanUtils.copyProperties(deptDto,dept);
        Boolean flag=deptMapper.insert(dept)>0 ?true:false;
        return flag;
    }

    @Override
    public List<DeptVo> selectAll() {
        List<Dept> depts=deptMapper.DeptQueryAll();
        List<DeptVo> deptVos=depts.stream().map(dept -> {
            DeptVo deptVo=new DeptVo();
            BeanUtils.copyProperties(dept,deptVo);
            deptVo.setStatus(dept.getState()==1?"使用中":"禁用");
            return deptVo;
        }).collect(Collectors.toList());
        return deptVos;
    }

    @Override
    public Boolean deleteById(String id) {
        return deptMapper.deleteById(id)>0?true:false;
    }
}
